package com.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

@WebListener
public class UserCountListener implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        int userCount = (int)application.getAttribute("userCount");
        userCount++;
        application.setAttribute("userCount",userCount);
        System.out.println("用户登录,系统当前在线人数:"+userCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        int userCount = (int)application.getAttribute("userCount");
        if(userCount != 0){
            userCount--;
        }else{
            userCount = 0;
        }
        application.setAttribute("userCount",userCount);
        System.out.println("用户注销,系统当前在线人数:"+userCount);
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        application.setAttribute("userCount",0);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        System.out.println("session添加属性");
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {

    }
}
